using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Lync.Widget.Library.Presentation.Entities;
using Lync.Widget.Library.Presentation.Models;
using Lync.Widget.Library.Presentation.Views;

namespace Lync.Widget.Library.Presentation.Presenters
{
    public class FiltersPresenter : IFiltersPresenter
    {
        public IFiltersView View { get; set; }
        public IFiltersModel Model { get; set; }

        public FiltersPresenter(IFiltersView view, IFiltersModel model)
        {
            View = view;
            Model = model;
        }

        public void OnLoad()
        {
            View.ShowResults = false;

            try
            {
                View.Filters = Model.GetAll();
                UpdateView();
            }
            catch (Exception exception)
            {
                View.ErrorMessage = exception.Message;
            }
        }

        public bool AddFilter()
        {
            View.Saved = false;

            var newFilter = View.NewFilter;
            var allFilters = View.Filters;

            if (allFilters.Any(f => f.Id.ToLower() == newFilter.Id.ToLower()))
            {
                View.ErrorMessage = String.Format("Filter with id '{0}' already exists", newFilter.Id);
                return false;
            }

            if (allFilters.Any(f => f.Name.ToLower() == newFilter.Name.ToLower()))
            {
                View.ErrorMessage = String.Format("Filter with name '{0}' already exists", newFilter.Name);
                return false;
            }

            if (!allFilters.Contains(newFilter, new FilterComparer()))
            {
                View.AddToList(newFilter);
                return true;
            }

            View.ErrorMessage = String.Format("Duplicte Filter");
            return false;
        }

        public bool RemoveFilter(string id)
        {
            View.Saved = false;

            var allFilters = View.Filters;
            var filter = allFilters.SingleOrDefault(f => f.Id == id);

            if (filter != null)
            {
                allFilters.Remove(filter);
                View.Filters = allFilters;
                return true;
            }

            View.ErrorMessage = String.Format("Filter with id '{0}' was not found", id);
            return false;
        }

        public bool Save()
        {
            var filters = View.Filters;

            try
            {
                if (filters.Count > 0)
                {
                    Model.Save(filters);
                    View.ShowDownloadButton = true;
                }
                else
                {
                    Model.Remove();
                }

                View.ResetNewFilter();
                View.Saved = true;
                return true;
            }
            catch (Exception exception)
            {
                View.ErrorMessage = exception.Message;
            }
            return false;
        }

        public void Download(HttpContext context)
        {
            var xml = Model.GetConfigurationXml();

            if (xml != null)
            {
                context.Response.Clear();
                context.Response.ContentType = "text/xml";
                context.Response.AddHeader("content-disposition", String.Format("attachment;filename={0}", "Admapping.config"));
                context.Response.Buffer = true;
                xml.Save(context.Response.OutputStream);
                context.Response.End();
            }
        }

        public void UpdateView()
        {
            var filters = View.Filters;

            if (filters != null && filters.Count > 0)
            {
                View.Filters = filters;
                View.ShowResults = true;
                View.ShowSaveButton = true;
                View.ErrorMessage = null;

                if (Model.GetConfigurationXml() != null)
                {
                    View.ShowDownloadButton = true;
                }
            }
            else
            {
                View.ShowResults = false;
                View.ErrorMessage = "No filters found";
                View.ShowDownloadButton = false;
            }
        }

        public void ResetNewFilter()
        {
            View.ResetNewFilter();
        }
    }

    public class FilterComparer : IEqualityComparer<IFilter>
    {
        public bool Equals(IFilter x, IFilter y)
        {
            return x.Id.ToLower() == y.Id.ToLower()
                   && x.Name.ToLower() == y.Name.ToLower()
                   && x.QuerystringParam.ToLower() == y.QuerystringParam.ToLower()
                   && x.Wildcard.ToLower() == y.Wildcard.ToLower();
        }

        public int GetHashCode(IFilter obj)
        {
            return obj.GetHashCode();
        }
    }
}